<template>
  <div id="userInfo" style="background-image: url('/static/background/background.png'); min-height: 99vh; position: relative;">
    <div id="tableContainer" style="height: 90vh; overflow-y: scroll; position: absolute; top: 20px; left: 50%; transform: translateX(-50%);" align="center">
      <loading v-if="loading"></loading>
      <div id="userInfo_information">数据资源上报</div>
      <div class="line"></div>
      <el-form :model="form" ref="form" :rules="rules" label-width="100px" id="form" class="demo-ruleForm" :inline="true">
        <el-form-item label="数据资源名称：" prop="dataResourceName" class="custom-label-color" :rules="[{validator: rules.dataResourceName, trigger:'blur', required: true}]">
          <el-input size="small" class="w300" placeholder="请输入数据资源名称"  v-model.trim="form.dataResourceName"></el-input>
        </el-form-item>

        <el-form-item label="数据类型：" prop='dataType' class=" custom-label-color"  :rules="[{ required: true, message: '请选择数据类型', trigger: 'change' }]">
          <el-select v-model='form.dataType' placeholder='请选择'
                     class="w300">
            <el-option v-for='item in typeList' :label='item.localName' :key='item.value' :value='item.value' ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="数据分类：" prop='dataCategory' class=" custom-label-color"  :rules="[{ required: true, message: '请选择数据分类', trigger: 'change' }]">
          <el-select v-model='form.dataCategory' placeholder='请选择'
                     class="w300">
            <el-option v-for='item in categoryList' :label='item.localName' :key='item.value' :value='item.value' ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          label="使用权明细："
          prop='usageRightDetail'
          class="custom-label-color"
          :rules="[{
    required: true,
    message: '请选择使用权',
    trigger: 'change'
  }]">
          <el-select
            class="w300"
            v-model="form.usageRightDetail"
            multiple
            collapse-tags
            placeholder="请选择"
           >
            <el-option
              v-for="item in usageRightList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="价格：" prop="price" class=" custom-label-color"  :rules="[{validator: rules.price, trigger:'blur', required: true}]">
          <el-input size="small" class="w300" placeholder="请输入价格" v-model.trim="form.price"></el-input>
        </el-form-item>

        <el-form-item label="数据文件："  prop="dataAttachments"   class=" custom-label-color" >
          <el-upload
            class="upload-demo w300 " action="" :auto-upload=false accept=".doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf,.jpg,.png"
            :on-remove="handleRemove"
            :before-upload="dataHandlePreview"
            :on-change="dataHandlePreview"
            :file-list="dataAttachments">
            <el-button size="mini" type="primary">上传附件</el-button>
          </el-upload>
        </el-form-item>

        <el-form-item label="证明文件类型：" prop='proofType' class=" custom-label-color" :rules="[{ required: true, message: '请选择证明文件类型', trigger: 'change' }]">
          <el-select v-model='form.proofType' placeholder='请选择'
                     class="w300">
            <el-option v-for='item in proofTypeList' :label='item.localName' :key='item.value' :value='item.value'></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="证明文件：" prop="proofAttachments" class=" custom-label-color" >
          <el-upload
            class="upload-demo w300 " action="" :auto-upload=false accept=".doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf,.jpg,.png"
            :on-remove="handleRemove"
            :before-upload="proofHandlePreview"
            :on-change="proofHandlePreview"
            :file-list="proofAttachments">
            <el-button size="mini" type="primary">上传附件</el-button>
          </el-upload>
        </el-form-item>

        <el-form-item label="封面图片："prop="imageAttachments" class=" custom-label-color" >
          <el-upload
            class="upload-demo w300 " action="" :auto-upload=false accept=".jpg,.jpeg,.png"
            :on-remove="handleRemove"
            :before-upload="imageHandlePreview"
            :on-change="imageHandlePreview"
            :file-list="imageAttachments">
            <el-button size="mini" type="primary">上传图片</el-button>
          </el-upload>
        </el-form-item>

        <div style="margin-bottom: 30px;">
          <el-button style="margin-left: 10px;" size="small" type="primary" @click="updataClick">提交</el-button>
          <el-button style="margin-left: 10px;" size="small" @click="resetClick">返回</el-button>
        </div>
      </el-form>
    </div>
    <div style="float: right; margin-top: 20px;margin-right: 20px;">
      <el-link type="primary" :href="'/download/' + encodeURIComponent('证明文件说明.pdf')" class="vertical-link">
        证明文件说明
      </el-link>
      <el-link type="primary" :href="'/download/' + encodeURIComponent('确权说明.pdf')" class="vertical-link">
        确权说明
      </el-link>
      <el-link type="primary" :href="'/download/' + encodeURIComponent('数据资源权属说明.pdf')" class="vertical-link">
        数据资源权属说明
      </el-link>
    </div>
  </div>


</template>
<script>
import { getUserInfo, updateUserInfo, getUserInfoWithPrivateKey } from '@/api/login'
import parent from '@/public/parent.js'
import rules from '@/public/rules.js'
import request from '@/utils/request'

export function search(type) {
  return request({
    url: '/cloud/jcce/v1.0/kt1/dataResource/dict/' + type,
    method: 'get'
  })
}

export function createData(dataResourceName, userId, price, dataCategory ,usageRightDetail, proofType ,dataType, dataFiles) {
  return request({
    url: '/cloud/jcce/v1.0/kt1/dataResource',
    method: 'post',
    params: {
      dataResourceName: dataResourceName,
      userId: userId,
      price: price,
      dataType: dataType,
      dataCategory: dataCategory,
      usageRightDetail: usageRightDetail.toString(),
      proofType: proofType,
      proprietorshipStatus: 'PENDING'
    },
    data: dataFiles
  })
}
export default {
  name: 'userInfo',
  mixins: [parent, rules],
  data() {
    // 定义校验规则
    const validateFileUrl = (rule, value, callback) => {
      if (this.dataAttachments.length < 1) { // 我控制了FileList 长度代表文件个数
        callback(new Error('请上传数据文件'))
      } else {
        callback()
      }
    }

    // eslint-disable-next-line no-unused-vars
    const validatePFileUrl = (rule, value, callback) => {
      if (this.proofAttachments.length < 1) { // 我控制了FileList 长度代表文件个数
        callback(new Error('请上传证明文件'))
      } else {
        callback()
      }
    }

    // eslint-disable-next-line no-unused-vars
    const validateIFileUrl = (rule, value, callback) => {
      if (this.imageAttachments.length < 1) { // 我控制了FileList 长度代表文件个数
        callback(new Error('请上传封面图片'))
      } else {
        callback()
      }
    }

    return {
      rules: {
        confirmPassword: (rule, value, callback) => {
          if (value === '') {
            callback(new Error('请再次输入密码'))
          } else if (value !== this.form.password) {
            callback(new Error('两次输入密码不一致!'))
          } else {
            callback()
          }
        },
        dataResourceName: (rule, value, callback) => {
          if (value === '') {
            callback(new Error('请输入数据资源名称'))
          } {
            callback()
          }
        },
        price: (rule, value, callback) => {
          if (value === '') {
            callback(new Error('请输入价格')) // 这里的错误信息应该修改为与价格相关的提示，例如：“请输入价格”
          } else if (!/^\d+(\.\d{1,2})?$/.test(value)) {
            // 使用正则表达式校验价格格式
            // 这个正则表达式匹配非负整数或者小数（最多两位小数）
            callback(new Error('价格格式不正确，请输入非负数，最多包含两位小数'))
          } else {
            callback() // 如果没有错误，继续执行
          }
        },
        dataAttachments: [{ required: true, validator: validateFileUrl, trigger: 'change' }],
        proofAttachments: [{ required: true, validator: validatePFileUrl, trigger: 'change' }],
        imageAttachments: [{ required: true, validator: validateIFileUrl, trigger: 'change' }],
        password: (rule, value, callback) => {
          if (value === '') {
            callback(new Error('请输入密码'))
          } else {
            callback()
          }
        }
      },
      loading: false,
      dialogVisible: false,
      isDisabled: false,
      dataAttachments: [],
      proofAttachments: [],
      imageAttachments: [],
      usageRightList:[{ value: '访问权', label: '访问权（有权访问和查看数据）' },
        { value: '分享权', label: '分享权（有权将数据分享给第三方或公众）' },
        { value: '保存权', label: '保存权（有权保留数据一段时间以备后续使用）' },
        { value: '迁移权', label: '迁移权（有权将数据从一个平台迁移到另一个平台）' },
        { value: '整合权', label: '整合权（有权将不同来源的数据整合起来使用）' },
        { value: '分析权', label: '分析权（有权对数据进行分析和推理）' },
        { value: '格式化权', label: '格式化权（有权选择和改变数据的存储和呈现格式）' },
        { value: '备份权', label: '备份权（有权对数据进行定期备份以防丢失）' },
        { value: '加注权', label: '加注权（有权对数据进行注释或添加元数据）' },
        { value: '复制权', label: '复制权（有权复制数据以用于备份、分析或其他用途）' }
      ],
      form: {
        proofType: '',
        dataResourceName: '',
        proprietorshipStatus: 'PENDING',
        price: '',
        dataType: '',
        dataCategory: '',
        usageRightDetail: [],// 使用权明细
        description: '',
        userId: ''
      },
      categoryList: [],
      proofTypeList: [],
      typeList: [],
      authorityList: [],
      applyList: []
    }
  },
  created() {
  },
  mounted() {
    // this.createDefaultMLoading(null)
    this.getCurrentUserInfo()
    this.getBaseDatas()
  },
  methods: {
    validateDataAttachments(rule, value, callback) {
      debugger
      if (this.dataAttachments.length === 0) {
        callback(new Error('请上传数据文件'))
      } else {
        callback()
      }
    },
    handleRemove(file, fileList) {
    },
    imageHandlePreview(file, files) {
      if (!!file && file.size > 5 * 1024 * 1024) {
        this.$message({ showClose: true, message: '上传文件不超过5M', type: 'error' })
        files.pop()
      }
      this.imageAttachments = files
    },
    dataHandlePreview(file, files) {
      this.dataAttachments = files
    },
    proofHandlePreview(file, files) {
      if (!!file && file.size > 5 * 1024 * 1024) {
        this.$message({ showClose: true, message: '上传文件不超过5M', type: 'error' })
        files.pop()
      }
      this.proofAttachments = files
    },
    getBaseDatas() {
      // 分类
      search('category').then((data) => {
        this.categoryList = data.data
        // this.categoryList.unshift(this.firstInfo)
      }).catch((error) => {
        console.log(error)
      })
      // 类型
      search('type').then((data) => {
        this.typeList = data.data
        // this.typeList.unshift(this.firstInfo)
      }).catch((error) => {
        console.log(error)
      })
      // 证明文件类型
      search('proofType').then((data) => {
        this.proofTypeList = data.data
        // this.typeList.unshift(this.firstInfo)
      }).catch((error) => {
        console.log(error)
      })

      // 确权状态
      this.authorityList = [
        { id: '0', label: '全部', value: '' },
        { id: '1', label: '待确认', value: 'PENDING' },
        { id: '2', label: '确权中', value: 'CONFIRMING' },
        { id: '3', label: '已通过', value: 'APPROVED' },
        { id: '4', label: '驳回', value: 'REJECTED' }
      ]
      // 申请状态
      this.applyList = [
        { id: '0', label: '全部', value: '' },
        { id: '1', label: '未提交', value: 'NOT_SUBMITTED' },
        { id: '2', label: '已提交', value: 'SUBMITTED' },
        { id: '3', label: '审核通过', value: 'AUDIT_APPROVE' },
        { id: '4', label: '已驳回', value: 'REJECTED' },
        { id: '5', label: '可下载', value: 'DOWNLOADABLE' }
      ]
    },
    updataClick() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          // this.mloading.show()
          var _self = this
          const dataFiles = new FormData()
          if (!!_self.dataAttachments && _self.dataAttachments.length > 0) {
            dataFiles.append('dataFile', _self.dataAttachments[0].raw)
          }

          // const proofFile = new FormData()
          if (!!_self.proofAttachments && _self.proofAttachments.length > 0) {
            dataFiles.append('proofFile', _self.proofAttachments[0].raw)
          }

          // const imageFile = new FormData()
          if (!!_self.imageAttachments && _self.imageAttachments.length > 0) {
            dataFiles.append('imageFile', _self.imageAttachments[0].raw)
          }

          debugger
          // _self.form.userId  = 44534646456;
          createData(
            _self.form.dataResourceName,
            _self.form.id, // userId
            _self.form.price,
            _self.form.dataCategory,
            _self.form.usageRightDetail,
            _self.form.proofType,
            _self.form.dataType,
            dataFiles).then(res => {
            // _self.mloading.hide()
            if (res.code === 0) {
              this.$message({
                message: '创建成功',
                type: 'success'
              })
              this.$router.push({ name: 'authentic', params: { previousPage: 'pubCloud', routeLevel: 3 }})
            } else {
              this.$message({ showClose: true, message: error.msg, type: 'error' })
            }
          })
        }
      })
    },
    resetClick() {
      this.$router.push({ name: 'authentic', params: { previousPage: 'pubCloud', routeLevel: 3 }})
    },
    showPrivateKey() {
      this.$confirm('确认查看用户私钥操作，仅可查看一次，请务必妥善保存私钥?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // this.mloading.show()
        var _self = this
        getUserInfoWithPrivateKey().then(res => {
          // _self.mloading.hide()
          this.form.privateKey = res.data.privateKey
          this.dialogVisible = true
        }).catch((error) => {
          // _self.mloading.hide()
          this.$message.error(error.msg)
          console.error(error.msg)
        }).then(() => {
        })
      })
    },
    getCurrentUserInfo() {
      // this.mloading.show()
      var _self = this
      getUserInfo().then(res => {
        // _self.mloading.hide()
        this.form.id = res.data.id
        this.form.username = res.data.username
        this.form.password = res.data.password
        this.form.confirmPassword = res.data.password
        this.form.name = res.data.name
        this.form.email = res.data.email
        this.form.phone = res.data.phone
        this.form.wechat = res.data.wechat
        this.form.authorities = res.data.authorities
        this.form.state = res.data.state
        this.form.publicKey = res.data.publicKey
        this.isDisabled = res.data.privateKeyStatus === 1
      })
    }
  },
  watch: {
    dataAttachments(nowval, oldval) {
      this.$refs['form'].validateField('dataAttachments');
    },
    imageAttachments(nowval, oldval) {
      this.$refs['form'].validateField('imageAttachments');
    },
    proofAttachments(nowval, oldval) {
      this.$refs['form'].validateField('proofAttachments');
    }
  }
}
</script>

<style lang="scss">
.custom-label-color .el-form-item__label {
  color: #FFFFFF; /* 白色 */
}
::v-deep .el-form-item__label {
  color: #FFFFFF; /* 白色 */
}

#userInfo {
  #expireNoteContainer {
    width: 100%;
    font-size: 35px;
    padding-top: 25px;
  }

  .line {
    align: center;
    height: 1px;
    background: #CED2DB;
    overflow: hidden;
    width: 680px;
    margin: 0 auto;
  }

  #tableContainer {
    width: 780px;
    border: 1px solid #B3BFD7;
    margin: 0px auto 20px;

    -moz-box-shadow: 4px 4px 2px #F1F1F3;
    //box-shadow: 4px 4px 2px #F1F1F3;
  }

  #userInfo_information {
    margin: 0;
    color: #8C95A6;
    text-align: center;
    padding: 18px 0 13px;
    font-size: 24px;
  }

  #ipsLabel, #macsLabel {
    vertical-align: top;
  }

}
.vertical-link {
  display: block;
  margin-bottom: 10px; /* Adjust the spacing between links as needed */
}
</style>
